package com.gree.shyun.service;

import com.gree.shyun.bean.*;
import com.alibaba.fastjson.JSON;
import com.gree.shyun.server.db.DbHelper;
import com.gree.shyun.server.db.sqlite.Selector;
import com.gree.shyun.server.db.sqlite.WhereBuilder;
import com.gree.shyun.server.db.table.DbModel;
import com.gree.shyun.server.db.util.LogUtils;
import com.gree.shyun.server.db.util.TextUtils;
import com.gree.shyun.server.fiddler.GetApiByFiddler;
import com.gree.shyun.server.taskpool.async.bean.Result;
import com.gree.shyun.entity.*;
import org.apache.commons.io.FileUtils;
import com.gree.shyun.util.*;
import com.gree.shyun.util.json.JsonMananger;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

public class ProcessService {
    //放全局 以便其他地方使用
    public static FileInfo fileInfo;
    public Result handle(String method,Object data,String resRoot ){
        switch (method){
            case "ExecLayoutToVM":
                String layoutPath = data.toString();
                File layoutfile = new File(layoutPath);
                String mPath = layoutfile.getParent();
                File pFile = new File(mPath);
                String[] files = pFile.list();
                for(String p:files){
                    try {
                        int maxLenth = 500;
                        String childPath = mPath+"\\"+p;
                        File childFile = new File(childPath);
                       String text =  FileUtils.readFileToString(childFile);
                       if(text.length()<maxLenth){
                           maxLenth = text.length();
                       }
                       String leftText = text.substring(0,maxLenth);
                       if(!leftText.contains("<layout")){
                           List<String> xmlns = LayoutHelper.getXmlns(leftText);
                           String xms = "";
                           for(String xm:xmlns){
                               leftText = leftText.replaceAll(xm,"");
                               xms+=xm+"\n";
                           }
                           String top = "<\\?xml version=\"1\\.0\" encoding=\"utf-8\"\\?>";
                           String replacetop = top+"\n<layout "+xms+">";
                           replacetop+="\n<data></data>";
                           leftText = leftText.replaceAll(top,replacetop);
                           text = leftText+text.substring(maxLenth);
                           text+="</layout>";
                           FileUtils.writeStringToFile(childFile,text);
                       }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                break;

            case "ExecActivityToVM":
                VMActivityHelper.doInit(data.toString(),resRoot);
                break;
            case "getAsFileInfo":
                FileInfo fileInfo = ASFileUtil.getFileInfo();
                if(fileInfo!=null){
                    ProcessService.fileInfo = fileInfo;
                    return success(method,fileInfo);
                }else{
                    return error(method,0,"Android studio 未打开");
                }
            case "setAsFileInfo":
                String temppath = data.toString();

                ProcessService.fileInfo = new FileInfo();
                ProcessService.fileInfo.setRootPath(temppath);
                ProcessService.fileInfo.setFilePath("/app");
                ProcessService.fileInfo.setModelPath(temppath+"/app/src/main");
                return success(method,"设置成功!"+JsonMananger.beanToJson(ProcessService.fileInfo));
            case "getAsLog":
                String mlog = data.toString();
                String log = ASFileUtil.getLog(mlog);
                return success(method,log);
            case "getView":
                String path = data.toString();
                View view = JsonXmlUtils.getViewFromPath(path);
                return success(method,view);
            case "analysisFiddler":
                String zipPath = data.toString();
                try {
                     GetApiByFiddler.saveAllApis(resRoot,zipPath);
                    return success("openFile","解析成功!");
                } catch (IOException e) {
                    e.printStackTrace();
                    return error("openFile",500,"解压出错!"+e.getMessage());
                }
            case "getDomainInfo":
                String sql = "select distinct domainMd5,domain from "+DbHelper.getTableName(ApiGroup.class)+" where isDel = 0 order by updateDate";
                List<DbModel> models = DbHelper.findDbModelAll(sql);
                List<ApiGroup> domains = new ArrayList<>();
                ApiGroup all = new ApiGroup();
                all.setDomain("全部");
                all.setDomainMd5("");
                domains.add(all);
                for(DbModel d:models){
                    ApiGroup apiGroup = new ApiGroup();
                    apiGroup.setDomain(d.getString("domain"));
                    apiGroup.setDomainMd5(d.getString("domainMd5"));
                    domains.add(apiGroup);
                }
                return success(method,domains);
            case "saveApi":
                String json = data.toString();
                if(!TextUtils.isEmpty(json)){
                    ApiAction apiAction = JsonMananger.jsonToBean(json,ApiAction.class);
                    if(apiAction!=null){
                        ApiAction find = DbHelper.findById(ApiAction.class,apiAction.getId());
                        if(find!=null){
                            find.setUrl(apiAction.getUrl());
                            find.setRequest(apiAction.getRequest());
                            find.setRespone(apiAction.getRespone());
                            find.setRemark(apiAction.getRemark());
                            DbHelper.update(find);
                            return success(method,"修改成功!");
                        }else{
                            String pid = "useradd";
                            apiAction.setPid(pid);
                            String domain = null;
                            String split = "/api/";
                            String p = apiAction.getUrl();
                            if(p.contains("@")){
                                p = p.substring(0,p.indexOf("@"));
                            }
                            if(p.contains(split)){
                                p = p.substring(p.indexOf(split));
                                int index = p.lastIndexOf(split)+1;
                                domain = p.substring(0,index-1);
                                p = p.substring(index);
                            }
                            UrlSpit urlSpit = CommonUtil.getUrlSpit(p);
                            apiAction.setDomain(domain);
                            apiAction.setDomainMd5(MD5.encrypt(urlSpit.getDomain()));
                            apiAction.setUrl(urlSpit.getUrl());
                            apiAction.setId(MD5.encrypt(urlSpit.getUrl()));
                            apiAction.setUrlParam(urlSpit.getParam());
                            apiAction.setAlias(urlSpit.getAlias());

                            DbHelper.saveOrUpdate(apiAction);

                            ApiGroup apiGroup = new ApiGroup();
                            apiGroup.setId(pid);
                            apiGroup.setName("手动添加的API");
                            apiGroup.setDomainMd5(pid);
                            apiGroup.setDomain("手动添加的API");
                            DbHelper.saveOrUpdate(apiGroup);
                            return success(method,"添加成功!");
                        }
                    }
                }
                return error(method,400,"传入参数为空!");
            case "deleteSource":
                String domainMd5 = data.toString();
                List<ApiGroup> deleteapiGroups = DbHelper.findAll(Selector.from(ApiGroup.class).where("domainMd5","=",domainMd5));
                List<String> deleteids = new ArrayList<>();
                for(ApiGroup apiGroup:deleteapiGroups){
                    apiGroup.setDel(true);
                    deleteids.add(apiGroup.getId());
                }
                DbHelper.updateAll(deleteapiGroups);
                List<ApiAction> deleteapiActions = DbHelper.findAll(Selector.from(ApiAction.class).where("pid","in",deleteids));
                for(ApiAction apiAction:deleteapiActions){
                    apiAction.setDel(true);
                }
                boolean deleteApi = DbHelper.updateAll(deleteapiActions);
                if(deleteApi){
                    return success(method,"删除成功!");
                }else{
                    return success(method,"删除失败!");
                }
            case "getApiInfo":
                String domain = data.toString();
                Selector groupSelector = Selector.from(ApiGroup.class);
                boolean isDel = false ;
                GetApiInfoParam  param = null;
                if(!TextUtils.isEmpty(domain)){
                    param = JsonMananger.jsonToBean(domain,GetApiInfoParam.class);
                    if(param!=null){
                        if(!TextUtils.isEmpty(param.getSource())){
                            groupSelector.where("domainMd5","=",param.getSource());
                        }
                        isDel = param.isDel();
                    }
                }
                List<ApiGroup> apiGroups = DbHelper.findAll(groupSelector);
                List<String> ids = new ArrayList<>();
                for(int i = 0; i<apiGroups.size();i++) {
                    ApiGroup apiGroup = apiGroups.get(i);
                    ids.add(apiGroup.getId());
                }
                String sval = "%"+param.getSearchVal()+"%";
                List<ApiAction> apiInfoList = DbHelper.findAll(
                        Selector.from(ApiAction.class)
                                .where("isDel", "=", isDel)
                                .and(!TextUtils.isEmpty(sval)?
                                        WhereBuilder.b("domain","like",sval)
                                                .or("request","like",sval)
                                                .or("urlParam","like",sval)
                                                .or("respone","like",sval)
                                                .or("name","like",sval)
                                                .or("title","like",sval)
                                                .or("url","like",sval)
                                                .or("alias","like",sval)
                                                .or("tag","like",sval):null)
                                .and("pid","in",ids)
                        );
                for(int i = 0; i<apiGroups.size();i++) {
                    List<ApiAction> apiActions = new ArrayList<>();
                    for(ApiAction apiAction:apiInfoList){
                        if(apiGroups.get(i).getId().equals(apiAction.getPid())){
                            apiActions.add(apiAction);
                        }
                    }
                    if(apiActions.size()>0){
                        apiGroups.get(i).setDel(isDel);
                        apiGroups.get(i).setApiActions(apiActions);
                    }else{
                        apiGroups.remove(i);
                        i--;
                    }
                }
                return success(method,apiGroups);
            case "addHistory":
                //添加历史记录
                if(!TextUtils.isEmpty(data.toString())){
                    History history = JsonMananger.jsonToBean(data.toString(),History.class);
                    if(history!=null){
                        String id = MD5.encrypt(history.getKey()+history.getValue());
                        history.setId(id);
                        history.setUpdateDate(new Date());
                        boolean b = DbHelper.saveOrUpdate(history);
                        if(b){
                            return success(method,"保存成功!");
                        }
                    }
                }
                return error(method,0,"保存失败!");
            case "getLastHistory":
                //获取最后一个历史记录
                if(data!=null){
                    History history = DbHelper.findFirst(Selector.from(History.class).where("key","=",data.toString()).orderBy("updateDate",true));
                    if(history!=null){
                        return success(method,history.getValue());
                    }
                }
                return error(method,0,"获取失败!");
            case "generateFormPage":
                if(!TextUtils.isEmpty(data.toString())){
                    List<FormPage> formPages = JsonMananger.jsonToList(data.toString(),FormPage.class);
                    if(formPages!=null&&formPages.size()>0) {
                        String form = FormUtil.formPageToCode(formPages);
                        String clName = formPages.get(0).getPage_class();
                        String file = resRoot+"form_code/";
                        File f = new File(file);
                        if(!f.exists()){
                            f.mkdirs();
                        }
                        try {
                            file =file+clName+".java";
                            JsonXmlUtils.stringToFile(form,new File(file));
                            return success(method,"生成成功!文件在:"+file);
                        } catch (IOException e) {
                            e.printStackTrace();
                            return error(method,500,"生成失败:"+e.getMessage());
                        }
                    }else{
                        return error(method,0,"数据为空!");
                    }
                }else {
                    return error(method,0,"参数为空!");
                }
            case "generateForm":
                LogUtils.e(data.toString());
                if(!TextUtils.isEmpty(data.toString())){
                    try {
                            FormData formData = JsonMananger.jsonToBean(data.toString(),FormData.class);
                            if(formData!=null&&formData.getForms()!=null&&formData.getForms().size()>0) {
                                String form = FormUtil.formToCode(formData);
                                String clName = formData.getClassName();
                                String file = resRoot+"form_code/";
                                File f = new File(file);
                                if(!f.exists()){
                                    f.mkdirs();
                                }
                                file =file+clName+".java";
                                JsonXmlUtils.stringToFile(form,new File(file));
                                return success(method,"生成成功!文件在:"+file);
                        }else{
                            return error(method,0,"数据为空!");
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        return error(method,500,"生成失败:"+e.getMessage());
                    }
                }else {
                    return error(method,0,"参数为空!");
                }
            case "getHistoryList":
                //查询历史记录
                if(!TextUtils.isEmpty(data.toString())){
                    History history = JsonMananger.jsonToBean(data.toString(),History.class);
                    if(history!=null){
                        Selector selector = Selector.from(History.class).where("key","=",history.getKey());
                        if(!TextUtils.isEmpty(history.getValue())){
                            selector.and("value","like",history.getValue());
                        }
                        List<History> histories = DbHelper.findAll(selector);
                        return success(method,histories);
                    }
                }
                return error(method,0,"查询失败");
            case "removeHistory":
                //删除历史记录
                if(data!=null){
                    String id = data.toString();
                    DbHelper.deleteById(History.class,id);
                    return success(method,"删除成功!");
                }else{
                    DbHelper.deleteAll(History.class);
                    return success(method,"已全部清空!");
                }
            case "delApi":
                if(data!=null){
                    String id = data.toString();
                    ApiAction apiAction = DbHelper.findById(ApiAction.class,id);
                    if(apiAction==null){
                        return error(method,-1,"不存在此数据");
                    }
                    if(apiAction.isDel()){
                        DbHelper.delete(apiAction);
                        return  success(method,"删除成功!");
                    }
                    apiAction.setDel(true);
                    DbHelper.update(apiAction);
                    return success(method,"屏蔽成功!");
                }else{
                    return  error(method,0,"ID为空!");
                }
            case "delApiByGroupId":
                if(data!=null){
                    String id = data.toString();
                    ApiGroup apiGroup = DbHelper.findById(ApiGroup.class,id);
                    if(apiGroup==null){
                        return error(method,-1,"不存在此数据");
                    }
                    List<ApiAction> apiActions = DbHelper.findAll(
                            Selector.from(ApiAction.class)
                                    .where("pid","=",apiGroup.getId()).and("isDel","=",false));
                    if(apiActions==null||apiActions.size()==0){
                        return error(method,0,"该组全部接口已经屏蔽");
                    }
                    for(ApiAction apiAction:apiActions){
                        apiAction.setDel(true);
                    }
                    DbHelper.updateAll(apiActions);
                    return success(method,"屏蔽组成功!");
                }else{
                    return  error(method,0,"ID为空!");
                }
            case "getRootUrl":
                //获取root url
                List<ApiRoot> apiRoots = DbHelper.findAll(ApiRoot.class);
                return success(method,apiRoots);
            case "deleteRootUrl":
                String rootUrlId = data.toString();
                boolean deleteRootUrl = DbHelper.deleteById(ApiRoot.class,rootUrlId);
                if(deleteRootUrl){
                    return success(method,"删除成功!");
                }else{
                    return error(method,500,"删除失败");
                }
            case "addRootUrls":
                List<ApiRoot> apiRootLists = JsonMananger.jsonToList(data.toString(),ApiRoot.class);
                for(ApiRoot apiRoot:apiRootLists){
                    ApiRoot apiRootList = DbHelper.findFirst(Selector.from(ApiRoot.class).where("key","=",apiRoot.getKey()));
                    if(apiRootList!=null){
                       apiRoot.setId(apiRootList.getId());
                    }else{
                        apiRoot.setId(UUID.randomUUID().toString());
                    }
                    apiRoot.setUrlMd5(MD5.encrypt(apiRoot.getUrl()));
                    if(!TextUtils.isEmpty(apiRoot.getTestUrl())){
                        apiRoot.setTestUrlMd5(MD5.encrypt(apiRoot.getTestUrl()));
                    }
                    if(!TextUtils.isEmpty(apiRoot.getDevUrl())){
                        apiRoot.setDevUrlMd5(MD5.encrypt(apiRoot.getDevUrl()));
                    }
                }
                boolean apiRootSavePl = DbHelper.saveOrUpdate(apiRootLists);
                if(apiRootSavePl){
                    return success(method,"批量更新成功!");
                }else{
                    return error(method,500,"批量更新失败");
                }
            case "changeAlias":
                if(TextUtils.isEmpty(data.toString())){
                    return error(method,400,"内容为空!");
                }
                ChangeAlias changeAlias = JsonMananger.jsonToBean(data.toString(),ChangeAlias.class);
                if(changeAlias!=null){
                    ApiAction apiAction = DbHelper.findById(ApiAction.class,changeAlias.getId());
                    if(apiAction!=null){
                        apiAction.setAlias(changeAlias.getVal());
                        DbHelper.update(apiAction);
                        return error(method,200,"修改成功!");
                    }
                }
                return error(method,500,"修改失败!");
            case "addRootUrl":
                ApiRoot apiRoot = JsonMananger.jsonToBean(data.toString(),ApiRoot.class);
                if(TextUtils.isEmpty(apiRoot.getKey())&&TextUtils.isEmpty(apiRoot.getUrl())){
                    return error(method,400,"key和url不能为空!");
                }
                String opr = "修改";
                if(TextUtils.isEmpty(apiRoot.getId())){
                    apiRoot.setId(UUID.randomUUID().toString());
                    opr = "添加";
                    ApiRoot apiRootList = DbHelper.findFirst(Selector.from(ApiRoot.class).where("key","=",apiRoot.getKey()));
                    if(apiRootList!=null){
                        return error(method,400,"已存在key:"+apiRoot.getKey());
                    }
                }

                apiRoot.setUrlMd5(MD5.encrypt(apiRoot.getUrl()));
                if(!TextUtils.isEmpty(apiRoot.getTestUrl())){
                    apiRoot.setTestUrlMd5(MD5.encrypt(apiRoot.getTestUrl()));
                }
                if(!TextUtils.isEmpty(apiRoot.getDevUrl())){
                    apiRoot.setDevUrlMd5(MD5.encrypt(apiRoot.getDevUrl()));
                }
                boolean apiRootSave = DbHelper.saveOrUpdate(apiRoot);
                if(apiRootSave){
                    return success(method,opr+"成功!");
                }else{
                    return error(method,500,opr+"失败");
                }
        }
        return error(method,-1,"方法未定义");
    }

    /**
     *  返回成功消息
     * @param method
     * @param result
     * @return
     */
    public static Result success(String method,Object result){
        Message message = new Message();
        message.setCode(200);
        message.setMessage("执行成功!");
        String json;
        if(result instanceof String){
            String res = result.toString();
            res = res.replaceAll("\r|\n", "");
            message.setData(res);
        }else{
            message.setData(result);
        }
        json = JSON.toJSON(message).toString();
        //文件路径处理 把 \\ 转 /
        json = json.replaceAll("\\\\\\\\","/");
        LogUtils.e(method+":"+json);
        json = json.replaceAll("\\\"","\\\\\\\"");
       return Result.put(method).put("result",json);
    }

    /**
     * 返回失败消息
     * @param method
     * @param code
     * @param msg
     * @return
     */
    public static Result error(String method,int code,String msg){
        Message message = new Message();
        message.setCode(code);
        message.setMessage(msg);
        String json = JsonMananger.beanToJsonStr(message);
        LogUtils.e(json);
        return  Result.put(method).put("result",json);
    }
}
